package com.atguigu.daijia.customer.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {
    private final CustomerInfoFeignClient customerInfoFeignClient;

    private final RedisTemplate redisTemplate;

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public String login(String code) {
        //1.远程调用
        Result<Long> loginResult = customerInfoFeignClient.login(code);
        //2.失败返回提示
        if(loginResult.getCode() != 200){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //3.id为空返回提示
        Long customerId = loginResult.getData();
        if(customerId == null){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //4.生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        //5.存入redis
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token,
                customerId.toString(),
                RedisConstant.USER_LOGIN_REFRESH_KEY_TIMEOUT, TimeUnit.SECONDS);
        //6.返回token
        return token;
    }

    /**
     * 获取用户登录信息
     *
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo() {
        //1.获取用户id
        Long customerId = AuthContextHolder.getUserId();
        //2.根据id远程调用查询用户登录信息
        Result<CustomerLoginVo> result =
                customerInfoFeignClient.getCustomerLoginInfo(customerId);
        //3.如果查询失败，提示错误信息
        if(result.getCode() != 200 || result.getData() == null){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        return result.getData();
    }
}
